package com.i1510.jobhandler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.i1510.service.IHsyService;
import com.i1510.util.SignUtils;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 *
 * XxlJob开发示例（Bean模式）
 *
 * 开发步骤：
 *      1、任务开发：在Spring Bean实例中，开发Job方法；
 *      2、注解配置：为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 *      3、执行日志：需要通过 "XxlJobHelper.log" 打印执行日志；
 *      4、任务结果：默认任务结果为 "成功" 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果；
 *
 */

@Component
public class HsyJob {
    private static Logger logger = LoggerFactory.getLogger(HsyJob.class);


    @Value("${hsy.tokenKey}")
    String hsyTokenKey;

    @Value("${hsy.jwt}")
    String hsyJwt;

    @Value("${hsy.merId}")
    String hsyMerId;

    @Value("${hsy.url}")
    String hsyUrl;

    @Value("${hsy.api.order.getOrderListByPay}")
    String hsyApiOrderGetOrderListByPay;

    @Value("${hsy.api.order.getOrderListByChange}")
    String hsyApiOrderGetOrderListByChange;

    @Autowired
    private IHsyService iHsyService;

    /**
     * 拉取指定期间的订单-付款
     */
    @XxlJob("hsyOrderJobHandler")
    public void hsyOrderJobHandler() throws Exception {
        try {
            XxlJobHelper.log("【拉取订单】任务开始:"+hsyApiOrderGetOrderListByPay);


            //调用的参数,按ascii码从小到大排序
            SortedMap<String, Object> params = new TreeMap<>();
            params.put("merId",hsyMerId);

            String jobParam = XxlJobHelper.getJobParam();
            XxlJobHelper.log("任务参数：{}", jobParam);
            if (StrUtil.isNotBlank(jobParam)) {
                JSONObject jsonObject = JSONObject.parseObject(jobParam);
                params.put("startTime",jsonObject.getString("sdate"));
                params.put("endTime",jsonObject.getString("edate"));
            }else{
                params.put("startTime",DateUtil.yesterday().toString("yyyy-MM-dd")+" 00:00:00");
                params.put("endTime",DateUtil.today()+" 23:59:59");
            }


            //当前时间
            long curTime = System.currentTimeMillis() / 1000;
            //header
            Map<String, String> pHeader = new HashMap<>();
            pHeader.put("Content-Type", "application/json");
            pHeader.put("mku", SignUtils.tokenValue());

            //body
            Map<String, Object> pBody = new HashMap<>();
            pBody.put("sign", SignUtils.sign(params,curTime));
            pBody.put("json", JSONObject.toJSON(params));
            pBody.put("time", curTime);


            XxlJobHelper.log("【发送header参数】:"+pHeader.toString());
            XxlJobHelper.log("【发送body参数】:"+pBody.toString());
            //send
            String post = HttpRequest.post(hsyApiOrderGetOrderListByPay).addHeaders(pHeader)
                    .body(JSONObject.toJSONString(pBody))
                    .execute().body();
            JSONObject rtn = JSONObject.parseObject(post);
            //System.out.println(rtn);
            if(200 == rtn.getInteger("code")){
                if(iHsyService.parseOrderList(rtn)){
                    XxlJobHelper.log("【拉取订单】任务结束:"+rtn.toString());
                }else{
                    XxlJobHelper.handleFail("【拉取订单】失败:"+rtn.toString());
                }

            }else{
                XxlJobHelper.handleFail("【拉取订单】失败:"+rtn.toString());
            }
            XxlJobHelper.handleSuccess();
        } catch (Exception e) {
            XxlJobHelper.handleFail(e.getMessage());
        } finally {

        }


    }


    /**
     * 拉取指定期间的订单-按最后修改时间
     */
    @XxlJob("hsyOrderChangeJobHandler")
    public void hsyOrderChangeJobHandler() throws Exception {
        try {
            XxlJobHelper.log("【拉取订单】任务开始:"+hsyApiOrderGetOrderListByChange);


            //调用的参数,按ascii码从小到大排序
            SortedMap<String, Object> params = new TreeMap<>();
            params.put("merId",hsyMerId);

            String jobParam = XxlJobHelper.getJobParam();
            XxlJobHelper.log("【任务参数】：{}", jobParam);
            if (StrUtil.isNotBlank(jobParam)) {
                JSONObject jsonObject = JSONObject.parseObject(jobParam);
                params.put("startTime",jsonObject.getString("sdate"));
                params.put("endTime",jsonObject.getString("edate"));
            }else{
                params.put("startTime",DateUtil.yesterday().toString("yyyy-MM-dd")+" 00:00:00");
                params.put("endTime",DateUtil.today()+" 23:59:59");
            }


            //当前时间
            long curTime = System.currentTimeMillis() / 1000;
            //header
            Map<String, String> pHeader = new HashMap<>();
            pHeader.put("Content-Type", "application/json");
            pHeader.put("mku", SignUtils.tokenValue());

            //body
            Map<String, Object> pBody = new HashMap<>();
            pBody.put("sign", SignUtils.sign(params,curTime));
            pBody.put("json", JSONObject.toJSON(params));
            pBody.put("time", curTime);


            XxlJobHelper.log("【发送header参数】:"+pHeader.toString());
            XxlJobHelper.log("【发送body参数】:"+pBody.toString());
            //send
            String post = HttpRequest.post(hsyApiOrderGetOrderListByChange).addHeaders(pHeader)
                    .body(JSONObject.toJSONString(pBody))
                    .execute().body();
            JSONObject rtn = JSONObject.parseObject(post);
            XxlJobHelper.log("【拉取订单】返回消息:"+rtn.toString());
            //System.out.println(rtn);
            if(200 == rtn.getInteger("code")){
                if(iHsyService.parseOrderList(rtn)){
                    XxlJobHelper.log("【拉取订单】保存成功:"+rtn.toString());
                }else{
                    XxlJobHelper.handleFail("【拉取订单】失败:"+rtn.toString());
                }

            }else{
                XxlJobHelper.handleFail("【拉取订单】失败:"+rtn.toString());
            }
            XxlJobHelper.handleSuccess();
        } catch (Exception e) {
            XxlJobHelper.handleFail(e.getMessage());
        } finally {

        }


    }


    public void init(){
        logger.info("init");
    }
    public void destroy(){
        logger.info("destroy");
    }


}
